package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: removeElements
 * @author: chanzhugang
 * @create: 2022/10/22 21:03
 */
public class RemoveElements {

    /**
     * 203 移除链表元素
     * https://leetcode.cn/problems/remove-linked-list-elements/
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        // 写链表代码三要素：1、指针的初始值；2、遍历的结束条件；3、遍历的核心逻辑
        // 虚拟头节点，找前置节点
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;
        ListNode prev = dummyHead;
        while (prev.next != null) {
            if (prev.next.val == val) {
                // 删除节点
                prev.next = prev.next.next;
            } else {
                prev = prev.next;
            }
        }
        return dummyHead.next;
    }

    public ListNode removeElements2(ListNode head, int val) {
        // 开辟新链表 + 尾指针 ：不满足的追加
        ListNode newNode = new ListNode();
        ListNode tail = newNode;
        ListNode p = head;
        while (p != null) {
            ListNode next = p.next;
            if (p.val != val) {
                // 尾插法
                p.next = null;
                tail.next = p;
                tail = p;
            }
            p = next;
        }
        return newNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}